﻿using BCCommon;
using BCCommon.Enums;
using BCData.TMS.EasyMoveSuiteConfig;
using BCDto.TMS.EasyMoveSuiteConfig;
using BCEntity.TMS.EasyMoveSuiteConfig;
using BCEntity.Common.EntityNameConst;
using BCService.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BCData.TMS.VehicleBusinessMapping;
using BCDto.Sim.Admin.Admin;
using BCDto.TMS.Agent.AgentAreaRecord;

namespace BCService.TMS.EasyMoveSuiteConfig
{
	public class EasyMoveSuiteConfigService : IEasyMoveSuiteConfigService
	{
		private readonly IDatabaseContext databaseContext;
		private readonly IRedisService redisService;
		private readonly IEasyMoveSuiteConfigData easyMoveSuiteConfigData;
		private readonly IVehicleBusinessMappingData vehicleBusinessMappingData;

		private readonly string key = string.Format("{0}", EntityNameConst.EasyMoveSuiteConfigEntity);

		public EasyMoveSuiteConfigService(IDatabaseContext databaseContext,
			IRedisService redisService,
			IEasyMoveSuiteConfigData easyMoveSuiteConfigData,
			IVehicleBusinessMappingData vehicleBusinessMappingData)
		{
			this.databaseContext = databaseContext;
			this.redisService = redisService;
			this.easyMoveSuiteConfigData = easyMoveSuiteConfigData;
			this.vehicleBusinessMappingData = vehicleBusinessMappingData;
		}

		#region 检查便捷搬家套餐配置是否存在
		public bool Exists(int easyMoveSuiteConfigId)
		{
			return this.easyMoveSuiteConfigData.Exists(easyMoveSuiteConfigId).GetAwaiter().GetResult();
		}
		#endregion

		#region 添加便捷搬家套餐配置
		public EasyMoveSuiteConfigDto Add(AdminDto adminDto, EasyMoveSuiteConfigRequestDto requestDto)
		{
			if (adminDto.AgentRecord == null)
			{
				throw new ArgumentException("非代理商无法执行此操作!");
			}
			if (!this.vehicleBusinessMappingData.Exists(requestDto.VehicleBusinessMappingId).GetAwaiter().GetResult())
			{
				throw new ArgumentException("车辆业务配置信息不存在!");
			}
			if (this.easyMoveSuiteConfigData.Exists(adminDto.AgentRecord.AgentRecordId, requestDto.ProvinceCode, requestDto.CityCode, requestDto.CountyCode, requestDto.VehicleBusinessMappingId).GetAwaiter().GetResult())
			{
				throw new ArgumentException("此套餐配置已存在!");
			}
			var vehicleBusinessMappingEntity = this.vehicleBusinessMappingData.GetEntity(requestDto.VehicleBusinessMappingId).GetAwaiter().GetResult();
			var entity = requestDto.As<EasyMoveSuiteConfigEntity>();
			entity.CreateAdminName = adminDto.FullName;
			entity.CreateAdminId = adminDto.AdminId;
			entity.AgentRecordId = adminDto.AgentRecord.AgentRecordId;
			entity.VehicleTypeId = vehicleBusinessMappingEntity.VehicleTypeId;
			return this.easyMoveSuiteConfigData.Add(entity).GetAwaiter().GetResult().As<EasyMoveSuiteConfigDto>();
		}
		#endregion

		#region 修改便捷搬家套餐配置
		public EasyMoveSuiteConfigDto Update(AdminDto adminDto, EasyMoveSuiteConfigPutDto putDto)
		{
			if (adminDto.AgentRecord == null)
			{
				throw new ArgumentException("非代理商无法执行此操作!");
			}
			if (!this.Exists(putDto.EasyMoveSuiteConfigId))
			{
				throw new ArgumentException("此记录不存在!");
			}
			if (!this.vehicleBusinessMappingData.Exists(putDto.VehicleBusinessMappingId).GetAwaiter().GetResult())
			{
				throw new ArgumentException("车辆业务配置信息不存在!");
			}
			var oldEntity = this.easyMoveSuiteConfigData.GetEntity(adminDto.AgentRecord.AgentRecordId, putDto.ProvinceCode, putDto.CityCode, putDto.CountyCode, putDto.VehicleBusinessMappingId).GetAwaiter().GetResult();
			if (oldEntity != null)
			{
				if (oldEntity.EasyMoveSuiteConfigId != putDto.EasyMoveSuiteConfigId)
				{
					throw new ArgumentException("此套餐配置已存在!");
				}
			}
			var vehicleBusinessMappingEntity = this.vehicleBusinessMappingData.GetEntity(putDto.VehicleBusinessMappingId).GetAwaiter().GetResult();
			var entity = putDto.As<EasyMoveSuiteConfigEntity>();
			entity.EditAdminName = adminDto.FullName;
			entity.EditAdminId = adminDto.AdminId;
			entity.AgentRecordId = adminDto.AgentRecord.AgentRecordId;
			entity.VehicleTypeId = vehicleBusinessMappingEntity.VehicleTypeId;
			var result = this.easyMoveSuiteConfigData.Update(entity).GetAwaiter().GetResult().As<EasyMoveSuiteConfigDto>();
			string cacheKey = this.redisService.GetKey(key, entity.EasyMoveSuiteConfigId);
			this.redisService.DeleteAsync(cacheKey);
			return result;
		}
		#endregion

		#region 删除便捷搬家套餐配置
		public bool Delete(AdminDto adminDto, int easyMoveSuiteConfigId)
		{
			if (adminDto.AgentRecord == null)
			{
				throw new ArgumentException("非代理商无法执行此操作!");
			}
			if (!this.Exists(easyMoveSuiteConfigId))
			{
				throw new ArgumentException("此记录不存在!");
			}
			var entity = this.Get(easyMoveSuiteConfigId);

			if (entity.AgentRecordId != adminDto.AgentRecord.AgentRecordId)
			{
				throw new ArgumentException("您无权删除此套餐配置!");
			}
			var result = this.easyMoveSuiteConfigData.Delete(easyMoveSuiteConfigId).GetAwaiter().GetResult();
			string cacheKey = this.redisService.GetKey(key, easyMoveSuiteConfigId);
			this.redisService.DeleteAsync(cacheKey);
			return result;
		}
		#endregion

		#region 获取便捷搬家套餐配置
		public EasyMoveSuiteConfigDto Get(int easyMoveSuiteConfigId)
		{
			string cacheKey = this.redisService.GetKey(key, easyMoveSuiteConfigId);
			var result = this.redisService.TryGet(cacheKey, () =>
			{
				var data = this.easyMoveSuiteConfigData.GetEntity(easyMoveSuiteConfigId).GetAwaiter().GetResult();
				return data;
			}, TimeSpan.FromDays(1));
			return result.As<EasyMoveSuiteConfigDto>();
		}
		public EasyMoveSuiteConfigDto Get(long agentRecordId, string suiteName)
        {
			string cacheKey = this.redisService.GetKey(key, agentRecordId, suiteName);
			var result = this.redisService.TryGet(cacheKey, () =>
			{
				var data = this.easyMoveSuiteConfigData.GetEntity(agentRecordId, suiteName).GetAwaiter().GetResult();
				return data;
			}, TimeSpan.FromDays(1));
			return result.As<EasyMoveSuiteConfigDto>();
		}
		#endregion

		#region 获取便捷搬家套餐配置列表
		public IEnumerable<EasyMoveSuiteConfigViewDto> GetList(long agentRecordId, string countyCode)
		{
			string cacheKey = this.redisService.GetKey(key, agentRecordId,countyCode);
			var result = this.redisService.TryGet(cacheKey, () =>
			{
				return this.easyMoveSuiteConfigData.GetList(agentRecordId, countyCode).GetAwaiter().GetResult();
			}, TimeSpan.FromDays(1));
			return result.As<IEnumerable<EasyMoveSuiteConfigViewDto>>();
		}
		#endregion

		#region 获取有便捷搬家套餐配置的代理商区域列表
		public IEnumerable<AgentAreaTreeDto> GetAgenAreaTreeList()
		{
			string cacheKey = this.redisService.GetKey(key, "AgentAreaTree");
			var result = this.redisService.TryGet(cacheKey, () =>
			{
				var list = this.easyMoveSuiteConfigData.GetList().Result;
				var provinceGroupList = list.GroupBy(p => p.ProvinceCode);
				List<AgentAreaTreeDto> tree = new List<AgentAreaTreeDto>();
				foreach (var item in provinceGroupList)
				{
					AgentAreaTreeDto province = new AgentAreaTreeDto();
					province.ProvinceCode = item.Key;
					province.ProvinceName = item.First().ProvinceName;
					List<AgentCityTreeDto> cityList = new List<AgentCityTreeDto>();
					var cityGroupList = item.GroupBy(p => p.CityCode);
					foreach (var cityItem in cityGroupList)
					{
						AgentCityTreeDto city = new AgentCityTreeDto();
						city.CityCode = cityItem.Key;
						city.CityName = cityItem.First().CityName;
						List<AgentCountyTreeDto> countyList = new List<AgentCountyTreeDto>();
						var countyGroupList = cityItem.GroupBy(p => p.CountyCode);
						foreach (var countyItem in countyGroupList)
						{
							AgentCountyTreeDto county = new AgentCountyTreeDto();
							county.CountyCode = countyItem.Key;
							county.CountyName = countyItem.First().CountyName;
							countyList.Add(county);
						}
						city.Children = countyList;
						cityList.Add(city);
					}
					province.Children = cityList;
					tree.Add(province);

				}
				return tree;
			}, TimeSpan.FromDays(1));
			return result;
		}
		#endregion

		#region 获取便捷搬家套餐配置分页
		public PageableList<EasyMoveSuiteConfigDto> Query(long? agentRecordId, string suiteName, string provinceCode, string cityCode, string countyCode, bool? enabled, DateTime? start, DateTime? end, string sortName, bool? ascending, int pageIndex, int pageSize)
		{
			string cacheKey = this.redisService.GetKey(key, agentRecordId, suiteName, provinceCode, cityCode, countyCode, enabled, start, end, sortName, ascending, pageIndex, pageSize);
			var result = this.redisService.TryGet(cacheKey, () =>
			{
				var data = this.easyMoveSuiteConfigData.Query(agentRecordId, suiteName, provinceCode, cityCode, countyCode, enabled, start, end, sortName, ascending, pageIndex, pageSize).GetAwaiter().GetResult();
				return new PageableList<EasyMoveSuiteConfigDto>
				{
					Count = data.Item2,
					Items = data.Item1.As<IEnumerable<EasyMoveSuiteConfigDto>>(),
					PageIndex = pageIndex,
					PageSize = pageSize,
					ServerTime = DateTime.Now
				};
			}, TimeSpan.FromMinutes(30));

			return result;
		}
		#endregion

		#region 启用便捷搬家套餐配置
		public bool Enabled(AdminDto adminDto, int easyMoveSuiteConfigId)
		{
			if (adminDto.AgentRecord == null)
			{
				throw new ArgumentException("非代理商无法执行此操作!");
			}
			if (!this.Exists(easyMoveSuiteConfigId))
			{
				throw new ArgumentException("此记录不存在!");
			}
			var entity = this.Get(easyMoveSuiteConfigId);

			if (entity.AgentRecordId != adminDto.AgentRecord.AgentRecordId)
			{
				throw new ArgumentException("您无权删除此套餐配置!");
			}
			var result = this.easyMoveSuiteConfigData.Enabled(easyMoveSuiteConfigId, adminDto.AdminId, adminDto.FullName).GetAwaiter().GetResult();
			string cacheKey = this.redisService.GetKey(key, easyMoveSuiteConfigId);
			this.redisService.DeleteAsync(cacheKey);
			return result;
		}
		#endregion

		#region 禁用便捷搬家套餐配置
		public bool Disabled(AdminDto adminDto, int easyMoveSuiteConfigId)
		{
			if (adminDto.AgentRecord == null)
			{
				throw new ArgumentException("非代理商无法执行此操作!");
			}
			if (!this.Exists(easyMoveSuiteConfigId))
			{
				throw new ArgumentException("此记录不存在!");
			}
			var entity = this.Get(easyMoveSuiteConfigId);

			if (entity.AgentRecordId != adminDto.AgentRecord.AgentRecordId)
			{
				throw new ArgumentException("您无权删除此套餐配置!");
			}
			var result = this.easyMoveSuiteConfigData.Disabled(easyMoveSuiteConfigId, adminDto.AdminId, adminDto.FullName).GetAwaiter().GetResult();
			string cacheKey = this.redisService.GetKey(key, easyMoveSuiteConfigId);
			this.redisService.DeleteAsync(cacheKey);
			return result;
		}
		#endregion
	}
}